/**
 * Copyright (C), 2015-2018, XXX有限公司
 * FileName: UserAction
 * Author:   70312
 * Date:     2018/6/13 11:20
 * Description: 用户类
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package cn.itcast.web.action;


import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br> 
 * 〈用户类〉
 */
@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class UserAction extends ActionSupport implements ModelDriven<User> {
    private User user = new User();
    @Override
    public User getModel() {
        return user;
    }

    @Autowired
    private UserService userService;
    /**
     * 功能描述: <br>
     * 〈用户注册方法〉
     */
    @Action(value = "user_regist",results = {@Result(name = "success",type = "json")})
    public String regist(){
        // 创建一个结果集
        Map<String,Object> result = new HashMap<>();
        // 校验用户名是否已经存在
        String username = user.getUsername();
        User existUser = userService.findByUsername(username);
        if(existUser != null) {
            result.put("msg",101); // 101: 用户名已经存在，注册失败
            ActionContext.getContext().getValueStack().push(result);
            return SUCCESS;
        }
        // 调用业务层
        userService.regist(user);

        result.put("msg",100); // 100:用户注册成功
        ActionContext.getContext().getValueStack().push(result);
        return SUCCESS;
    }


    /**
     * 功能描述: <br>
     * 〈用户登录的方法〉
     */
    @Action(value = "user_login",results = {@Result(name = "success",type = "json")})
    public String login() {
        User existUser = userService.login(user);
        Map<String,Object> result = new HashMap<>();
        if(existUser != null) {
            // 登陆成功
            ServletActionContext.getRequest().getSession().setAttribute("user", existUser);
            result.put("msg","400");  // 400: 登录成功
            result.put("user",existUser);
        }else {
            // 登录失败
            result.put("msg","500"); // 500：用户名或密码错误

        }
        ActionContext.getContext().getValueStack().push(result);
        return SUCCESS;

    }


}